package com.cms.util.updown;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

import org.apache.commons.logging.*;

public class DownloadServlet extends HttpServlet {
	
	private Log log = LogFactory.getFactory().getInstance(this.getClass().getName());

	protected void doGet(HttpServletRequest req, HttpServletResponse res) 
		throws ServletException, IOException {
		doPost(req, res);
	}
	
	protected void doPost(HttpServletRequest req, HttpServletResponse res)
		throws ServletException, IOException {
		try {
			process(req, res);
		} catch (Exception e) {
			throw new ServletException(e.getMessage());
		}
	}
	
	private void process(HttpServletRequest req, HttpServletResponse res)
		throws Exception {						
		try {
			String fileName = req.getParameter("fileName");
			
			String uploadPath = this.getServletConfig().getServletContext().getInitParameter("upload-download-target");
			String filePath = uploadPath + fileName;		
			
			File file = new File(filePath);
			
			fileName = fileName.substring(fileName.indexOf("-") + 1);
			fileName = new String(fileName.getBytes(), "8859_1");
			
			try {
				if (!file.exists() || !file.canRead()) {
					PrintWriter out = res.getWriter();
					out.println(
							"<script>alert('File Not Found');history.back();</script>");
					return;
				}
			} catch (Exception e) {
				PrintWriter out = res.getWriter();
				out.println("<script>alert('File Not Found');history.back();</script>");
				return;
			}
						
			String agentType = req.getHeader("User-Agent");			
			if (agentType != null && agentType.indexOf("gzip") >= 0) {
				res.setHeader("Content-Type", "doesn/matter;");
				res.setHeader("Content-Disposition", "filename=" + fileName + ";");
			} else {
				res.setHeader("Content-Type", "application/octet-stream");
				res.setHeader("Content-Disposition", "attachment;filename=" + fileName + ";");
			}
			
			res.setHeader("Content-Transfer-Encoding", "binary;");
			res.setHeader("Content-Length", "" + file.length() + ";");
			res.setHeader("Pragma", "no-cache;");
			res.setHeader("Expires", "-1;");
			
			dumpFile(file, res.getOutputStream());			
		} catch (Exception e) {
			log.debug(e.getMessage());
			PrintWriter out = res.getWriter();
			out.println("<script>alert('File Not Found');history.back();</script>");
			return;
		}
	}
	
	private void dumpFile(File realFile, OutputStream os) {
		BufferedInputStream bis = null;
		try {
			byte[] readByte = new byte[4098];
			bis = new BufferedInputStream(new FileInputStream(realFile));
			int i;
			while ((i = bis.read(readByte, 0, 4098)) != -1) 
				os.write(readByte, 0, i);
		} catch (Exception e) {
			
		} finally {
			try {
				bis.close();
				os.flush();
				os.close();
			} catch (IOException ie) {}
		}
	}
}